<template>
	<view class="login-container">
		<view class="login-box">
			<view class="title">欢迎登录</view>
			<view class="login-type">
				<text :class="['type-item', loginType === 'account' ? 'active' : '']"
					@click="loginType = 'account'">账号密码登录</text>
				<text :class="['type-item', loginType === 'phone' ? 'active' : '']"
					@click="loginType = 'phone'">手机号登录</text>
			</view>
			<view class="input-group">
				<!-- 账号密码登录 -->
				<template v-if="loginType === 'account'">
					<view class="input-item">
						<text class="iconfont icon-user"></text>
						<input type="text" v-model="username" placeholder="请输入用户名" />
					</view>
					<view class="input-item">
						<text class="iconfont icon-lock"></text>
						<input type="password" v-model="password" placeholder="请输入密码" />
					</view>
					<view class="input-item verify-code">
						<text class="iconfont icon-safe"></text>
						<input type="text" v-model="imageVerifyCode" placeholder="请输入验证码" maxlength="4" />
						<image class="verify-image" :src="verifyCodeUrl" @click="refreshVerifyCode" mode="aspectFit">
						</image>
					</view>
				</template>
				<!-- 手机号登录 -->
				<template v-else>
					<view class="input-item">
						<text class="iconfont icon-phone"></text>
						<input type="number" v-model="phone" placeholder="请输入手机号" maxlength="11" />
					</view>
					<view class="input-item verify-code">
						<text class="iconfont icon-safe"></text>
						<input type="number" v-model="verifyCode" placeholder="请输入验证码" maxlength="6" />
						<view class="get-code-btn" @tap="getVerifyCode" :class="{ disabled: counting }">
							{{ counting ? `${countdown}s后重新获取` : '获取验证码' }}
						</view>
					</view>
				</template>
			</view>
			<button class="login-btn" @click="handleLogin">登录</button>
			<view class="options">
				<text @click="goToRegister">注册账号</text>
				<text @click="goToForget">忘记密码</text>
			</view>
		</view>
	</view>
</template>

<script>
	import userApi from '@/api/user.js'
	import {
		v4 as uuidv4
	} from 'uuid';
	export default {
		data() {
			return {
				loginType: 'account', // account: 账号密码登录, phone: 手机号登录
				username: '',
				password: '',
				phone: '',
				loginState: false,
				verifyCode: '',
				imageVerifyCode: '',
				verifyCodeUrl: '',
				counting: false,
				countdown: 60,
				key: '',
				isRefreshing: false
			}
		},
		mounted() {
			this.refreshVerifyCode();
		},
		methods: {
			//验证码
			refreshVerifyCode() {
				// 防止重复点击
				if (this.isRefreshing) return;
				this.isRefreshing = true;
				this.key = uuidv4();
				console.log('刷新验证码，key:', this.key);
				userApi.getImageVerifyCode(this.key).then(res => {
					console.log(res);
					this.verifyCodeUrl = `data:image/png;base64,${res}`;
				}).catch(err => {
					console.log('获取验证码失败:', err);
					uni.showToast({
						title: '获取验证码失败',
						icon: 'none'
					});
				}).finally(() => {
					// 延迟重置状态，防止快速点击
					setTimeout(() => {
						this.isRefreshing = false;
					}, 1000);
				});
			},
			//登陆按钮
			async handleLogin() {
				//账号密码登录
				if (this.loginType === 'account') {
					// 验证账号格式：首字母，6-10位
					if (!/^[a-zA-Z][a-zA-Z0-9]{5,9}$/.test(this.username)) {
						uni.showToast({
							title: '账号必须以字母开头，6-10位',
							icon: 'none'
						});
						return;
					}
					// 验证密码长度：至少6位
					if (this.password.length < 6) {
						uni.showToast({
							title: '密码至少6位',
							icon: 'none'
						});
						return;
					}
					// 验证验证码是否输入
					if (this.imageVerifyCode.length < 4) {
						uni.showToast({
							title: '请输入验证码',
							icon: 'none'
						});
						return;
					}
					console.log("账号密码登录")
					//校验账号密码和验证码
					const data = {
						userAcc: this.username,
						password: this.password
					}
					userApi.loginByAccount(data, this.key, this.imageVerifyCode).then(res => {
						console.log(res);
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});
						// 存储token
						uni.setStorageSync('token', res.token);
						// 存储用户信息
						uni.setStorageSync('user', res.user);
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/firstPage/firstPage'
							});
						}, 500);
					}).catch(err => {
						console.log(err);
					})
				}
				//手机号登录	
				else {
					console.log("phna")
					//判断是否获取了验证码
					if (!this.loginState) {
						uni.showToast({
							title: '请先获取验证码',
							icon: 'none'
						});
						return;
					};
					//判断验证码是否输入
					if (!this.verifyCode) {
						uni.showToast({
							title: '请输入验证码',
							icon: 'none'
						});
						return;
					}
					//校验手机号和验证码
					const data = {
						code: this.verifyCode,
						phone: this.phone
					}
					console.log(data)
					try {
						await userApi.phoneLogin(data.phone,data.code).then(res =>{
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/firstPage/firstPage'
								});
							}, 500);
						})
					} catch (error) {
						console.error('校验失败:', error);
					}

				}
			},

			async getVerifyCode() {
				console.log("------------------");
				if (this.counting) return;
				if (!this.phone) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
					return;
				}
				if (!/^1[3-9]\d{9}$/.test(this.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}

				try {

					const data = await userApi.getPhoneVerifyCode(this.phone);
					console.log(data, "---123");
					this.counting = true;
					this.countdown = 60;
					this.loginState = true;
					//验证码倒计时功能
					const timer = setInterval(() => {
						this.countdown--;
						if (this.countdown <= 0) {
							clearInterval(timer);
							this.counting = false;
						}
					}, 1000);
				} catch (error) {
					console.error('获取验证码失败:', error);
				}
			},


			goToRegister() {
				uni.navigateTo({
					url: '/pages/register/register'
				});
			},
			goToForget() {
				uni.navigateTo({
					url: '/pages/forgetPwd/forgetPwd'
				});
			}

		}
	}
</script>

<style lang="scss">
	.login-container {
		min-height: 100vh;
		background: linear-gradient(135deg, #6e8efb, #a777e3);
		display: flex;
		align-items: center;
		justify-content: center;

		.login-box {
			width: 85%;
			padding: 40rpx;
			background-color: rgba(255, 255, 255, 0.95);
			border-radius: 20rpx;
			box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.2);

			.title {
				font-size: 40rpx;
				font-weight: bold;
				text-align: center;
				margin-bottom: 40rpx;
				color: #333;
			}

			.login-type {
				display: flex;
				justify-content: center;
				margin-bottom: 40rpx;

				.type-item {
					padding: 20rpx 40rpx;
					font-size: 28rpx;
					color: #666;
					position: relative;

					&.active {
						color: #007AFF;
						font-weight: bold;

						&::after {
							content: '';
							position: absolute;
							bottom: 0;
							left: 50%;
							transform: translateX(-50%);
							width: 40rpx;
							height: 4rpx;
							background-color: #007AFF;
							border-radius: 2rpx;
						}
					}
				}
			}

			.input-group {
				margin-bottom: 40rpx;

				.input-item {
					display: flex;
					align-items: center;
					border-bottom: 1px solid #eee;
					padding: 20rpx 0;
					margin-bottom: 30rpx;

					&.verify-code {
						position: relative;

						.verify-image {
							position: absolute;
							right: 0;
							top: 50%;
							transform: translateY(-50%);
							width: 200rpx;
							height: 60rpx;
							z-index: 2;
							cursor: pointer;
							object-fit: contain;
							background-color: #f5f5f5;
							border-radius: 4rpx;
						}

						.get-code-btn {
							position: absolute;
							right: 0;
							font-size: 24rpx;
							color: #007AFF;
							padding: 10rpx 20rpx;
							z-index: 2;

							&.disabled {
								color: #999;
							}
						}
					}

					.iconfont {
						font-size: 40rpx;
						color: #999;
						margin-right: 20rpx;
					}

					input {
						flex: 1;
						font-size: 28rpx;
					}
				}
			}

			.login-btn {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				background: linear-gradient(to right, #6e8efb, #a777e3);
				color: #fff;
				border-radius: 40rpx;
				font-size: 32rpx;
				margin-bottom: 30rpx;

				&:active {
					opacity: 0.8;
				}
			}

			.options {
				display: flex;
				justify-content: space-between;
				font-size: 26rpx;
				color: #666;

				text {
					padding: 10rpx;

					&:active {
						opacity: 0.7;
					}
				}
			}
		}
	}
</style>